//
//  RechangeWebVC.m
//  HengYouCai
//
//  Created by lwj on 2017/9/30.
//  Copyright © 2017年 lwj. All rights reserved.
//

#import "RechangeWebVC.h"

@interface RechangeWebVC ()<WKNavigationDelegate,WKUIDelegate,WKScriptMessageHandler>

@end

@implementation RechangeWebVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = self.strTitle;
    
    WKUserContentController *userContentController = [[WKUserContentController alloc] init];
    
    [userContentController addScriptMessageHandler:self name:@"appToAccount"];
    [userContentController addScriptMessageHandler:self name:@"appToPurchase"];
    [userContentController addScriptMessageHandler:self name:@"appToTel"];
    
    WKWebViewConfiguration * config = [[WKWebViewConfiguration alloc] init];
    config.userContentController = userContentController;
    
    _wkWebView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:config];
    _wkWebView.UIDelegate = self;
    _wkWebView.navigationDelegate = self;
    [self.view addSubview:self.wkWebView];
    
    if (self.strHtmlBody.length) {
        [self.wkWebView loadHTMLString:self.strHtmlBody baseURL:nil];
    }else if (self.webUrl.length){
        [self loadRequestWithUrlStr:self.webUrl];
    }
    
    
}

- (void)loadRequestWithUrlStr:(NSString *)urlStr{
    
    NSMutableURLRequest * request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:urlStr]];
    //用户token
    NSString *userToken = [WLFileManager readUserDataForKey:kUserSessionId];
    if (userToken!=nil) {
        [request setValue:userToken forHTTPHeaderField:kUserSessionId];
    }
    //渠道码
    [request setValue:kChannel_app forHTTPHeaderField:@"appChannel"];
    //来源
    [request setValue:@"iOS" forHTTPHeaderField:@"OSType"];
    //手机型号
    [request setValue:[NSObject wl_getDeviceModel] forHTTPHeaderField:@"deviceModel"];
    //手机系统版本
    [request setValue:[[UIDevice currentDevice] systemVersion] forHTTPHeaderField:@"OSVersion"];
    //应用程序版本
    NSDictionary *dict = [[NSBundle mainBundle] infoDictionary];
    NSString *app_Version = [dict objectForKey:@"CFBundleShortVersionString"];
    [request setValue:app_Version forHTTPHeaderField:@"appVersion"];
    //MARK:网页请求默认10s
    request.timeoutInterval = 10;
    
    [self.wkWebView loadRequest:request];
}

////MARK:交互
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
    if ([message.name isEqualToString:@"appToPurchase"]){//立即投资 两种情况 1.充值界面 过来跳账户 2. 投资界面过来 原路返回
        if (self.isFromAccount) {//1
            self.tabBarController.selectedIndex = 1;
            [self.navigationController popToRootViewControllerAnimated:YES];
        }else{//2
            
            [self popToViewControllerAtIndex:2];
        }
    }
    else if ([message.name isEqualToString:@"appToAccount"]){//回到账户
        self.tabBarController.selectedIndex = 2;
        [self.navigationController popToRootViewControllerAnimated:YES];
    }else if ([message.name isEqualToString:@"appToTel"]){//打电话
        NSString *callPhone = [NSString stringWithFormat:@"telprompt://%@", [WLFileManager readUserDataForKey:kPhone]];
        /// 防止iOS 10及其之后，拨打电话系统弹出框延迟出现
        dispatch_async(dispatch_get_main_queue(), ^{
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:callPhone]];
        });
    }
}

//HTML页面Alert出内容
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler{
    
    UIAlertController * alert = [UIAlertController alertControllerWithTitle:webView.title message:message preferredStyle:UIAlertControllerStyleAlert];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler();
    }]];
    [self presentViewController:alert animated:YES completion:nil];
    
}
//HTML页面弹出Confirm时调用此方法
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler{
    
    UIAlertController * alert = [UIAlertController alertControllerWithTitle:webView.title message:message preferredStyle:UIAlertControllerStyleAlert];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(YES);
    }]];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(NO);
    }]];
    
    [self presentViewController:alert animated:YES completion:nil];
}

//// 处理拨打电话以及Url跳转等等 // 在发送请求之前，决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    NSURL *URL = navigationAction.request.URL;
    NSString *scheme = [URL scheme];
    if ([scheme isEqualToString:@"tel"]) {
        NSString *resourceSpecifier = [URL resourceSpecifier];
        NSString *callPhone = [NSString stringWithFormat:@"telprompt://%@", resourceSpecifier];
        /// 防止iOS 10及其之后，拨打电话系统弹出框延迟出现
        dispatch_async(dispatch_get_main_queue(), ^{
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:callPhone]];
        });
    }
    //    if  {
    //        <#statements#>
    //    }
    //    NSString *urlStr = URL.absoluteString;
    //    if ([urlStr isEqualToString:@"https://api.ziyijinfu.com/payment/paymentAppNotify"]) {
    //        decisionHandler(WKNavigationActionPolicyAllow);
    //    }else{
    //
    //    }
    decisionHandler(WKNavigationActionPolicyAllow);
    
    //    decisionHandler(WKNavigationActionPolicyCancel);
}


@end

